<?php
/**
 * 
 * 简单数据库操作类
 * @author songerzhou
 *
 */
class db
{

	var $_version = "1.0";
	var $_type = "mysql";
	var $_host = "";
	var $_user = "";
	var $_pwd = "";
	var $_name = "";
	var $_conn = null;

	function db( $arrParams = array
	(
		"host" => "localhost",
		"user" => "root",
		"pwd" => "",
		"db" => "test"
	) )
	{
		$this->_host = $arrParams['host'];
		$this->_user = $arrParams['user'];
		$this->_pwd = $arrParams['pwd'];
		$this->_db = $arrParams['db'];
		$this->_open( $this->_db );
	}

	function query( $sql )
	{
		if ( !( $rs = mysql_db_query( $this->_db, $sql ) ) )
		{
			$this->_quit( "Query error: <span style='display:none'>".$sql."</span>" );
		}
		return $rs;
	}

	function fetchone( $sql )
	{
		$rs = $this->query( $sql );
		$arr = mysql_fetch_array( $rs, MYSQL_NUM );
		mysql_free_result( $rs );
		return $arr[0];
	}

	function fetchrow( $sql )
	{
		$rs = $this->query( $sql );
		$arr = mysql_fetch_array( $rs, MYSQL_ASSOC );
		mysql_free_result( $rs );
		return $arr;
	}

	function fetchrows( $sql )
	{
		$result = $this->query( $sql );
		$arr = array( );
		while ( $row = mysql_fetch_array( $result, MYSQL_ASSOC ) )
		{
			$arr[] = $row;
		}
		mysql_free_result( $result );
		return $arr;
	}

	function fetchpage( $sql, $page = "1", $pageSize = "20" )
	{
		$start = ( $page - 1 ) * $pageSize;
		$arr = $this->fetchrows( $sql.( " LIMIT ".$start.", {$pageSize}" ) );
		return $arr;
	}
	
	function getlastid( )
	{
		return mysql_insert_id( );
	}

	function close( )
	{
		mysql_close( );
	}

	function _open( $database = "test" )
	{
		$this->_conn = mysql_connect( $this->_host, $this->_user, $this->_pwd ) || $this->_quit( "Connect error: " );
		if ( 4.1 <= $this->_getdbversion( ) )
		{
			mysql_query( "SET NAMES utf8" );
		}
		return mysql_select_db( $database );
	}

	function _getdbversion( )
	{
		$rs = mysql_query( "SELECT VERSION();" );
		$row = mysql_fetch_array( $rs, MYSQL_NUM );
		$ver = $row[0];
		$vers = explode( ".", trim( $ver ) );
		$ver = $vers[0].".".$vers[1];
		return $ver;
	}

	function _quit( $msg = "Error: " )
	{
		exit( $msg.mysql_error( ) );
	}

}

?>
